<template>
  <el-card class="main-card">
    <div slot="header" class="card-header">
      <h2 class="card-header-title">今日科室出诊信息</h2>
    </div>

    <!-- 表格容器，添加滚动效果 -->
    <div class="table-scroll-container">
      <el-table
        v-loading="loading"
        :data="departmentData"
        border
        style="width: 100%;"
        :header-cell-style="{background: '#f0f2f5', color: '#333'}"
        :row-style="{height: '50px'}"
      >
        <el-table-column prop="department" label="科室" align="center"></el-table-column>
        <el-table-column prop="doctor" label="医生" align="center"></el-table-column>
        <el-table-column prop="title" label="职称" align="center"></el-table-column>
        <el-table-column prop="time" label="出诊时间" align="center"></el-table-column>
        <el-table-column prop="remaining" label="剩余号源" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.remaining > 5">{{ scope.row.remaining }}个</el-tag>
            <el-tag type="danger" v-else-if="scope.row.remaining > 0">{{ scope.row.remaining }}个</el-tag>
            <el-tag type="danger" v-else>已满</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import request from '@/utils/request'

const departmentData = ref([])
const loading = ref(false)
const errorMsg = ref('')
let refreshInterval = null

// 核心修改：从后端接口获取真实出诊数据（替换原模拟逻辑）
const fetchDepartmentData = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/system/daily/today',
      method: 'get',
      timeout: 10000
    })
    // 核心修复：把 res.data.data → res.data，且调整条件顺序（先判code，再判数组）
    if (res && res.code === 200 && Array.isArray(res.data)) {
      departmentData.value = res.data.map(item => ({
        department: item.department || '未知科室',
        doctor: item.doctor_name || '未知医生',
        title: item.title || '无职称',
        time: item.schedule_text || '暂无出诊时间',
        remaining: item.remaining !== undefined ? item.remaining : 0
      }))
      errorMsg.value = ''; // 成功后清空错误提示
    } else {
      errorMsg.value = '数据格式异常'
      console.error('接口返回格式错误：', res) // 修复：打印完整res，而非res.data.data（避免undefined）
      loadMockDepartmentData()
    }
  } catch (err) {
    errorMsg.value = err.message.includes('timeout') ? '请求超时' : '获取数据失败'
    console.error('出诊数据获取失败：', err)
    loadMockDepartmentData()
  } finally {
    loading.value = false
  }
}

// 新增：降级用模拟数据（与原模拟数据一致，避免接口异常时页面空白）
function loadMockDepartmentData() {
  departmentData.value = [
    { department: '内科', doctor: '张伟', title: '主任医师', time: '周一上午，周三下午', remaining: 8 },
    { department: '妇产科', doctor: '钱丽', title: '主任医师', time: '周二上午，周四上午', remaining: 1 },
    { department: '外科', doctor: '秦浩', title: '主任医师', time: '周五全天', remaining: 7 },
    { department: '眼科', doctor: '周明', title: '副主任医师', time: '周一下午，周三下午', remaining: 8 },
    { department: '口腔科', doctor: '陈刚', title: '主任医师', time: '周一上午，周三下午', remaining: 5 },
    { department: '妇产科', doctor: '刘宏', title: '副主任医师', time: '周三上午，周五下午', remaining: 5 },
    { department: '内科', doctor: '刘备', title: '副主任医师', time: '周三上午，周五下午', remaining: 9 },
    { department: '眼科', doctor: '朱帝', title: '副主任医师', time: '周一上午，周三下午', remaining: 6 }
  ]
}

onMounted(() => {
  // 初始加载数据
  fetchDepartmentData()
  
  // 每5秒刷新一次数据（实时更新剩余名额和统计）
  refreshInterval = setInterval(() => {
    fetchDepartmentData()
  }, 10 * 1000)
})

onUnmounted(() => {
  // 组件销毁时清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})

// 暴露方法给父组件使用
defineExpose({
  refresh: fetchDepartmentData
})
</script>

<style scoped lang="scss">
.main-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 6px;

  .card-header {
    background-color: #f7f8fa;
    border-bottom: 1px solid #e5e6eb;
    padding: 12px 20px;

    .card-header-title {
      font-size: 18px;
      font-weight: bold;
      color: #1f2d3d;
      margin: 0;
    }
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.table-scroll-container {
  max-height: 450px;
  overflow-y: auto;
  padding-right: 5px;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #a1a1a1;
  }
}
</style>